<template>
    <div class="page">
        <div class="bg-color-box">
            <!--顶部导航栏-->
            <van-nav-bar class="nav-bar-box" :left-arrow="true" @click-left="onClickLeft">
                <div slot="left">
                    <i class="go-back-icon"></i>
                    <span class="title">注册</span>
                </div>
            </van-nav-bar>
        </div>

        <!--注册表单信息-->
        <div class="module-box">
            <van-cell-group>
                <van-field label="姓名" v-model="formInfo.personName" required/>

                <van-field v-model="formInfo.personPhone" center clearable label="手机号" required>
                    <span v-if="showCountdown" class="get-captcha" slot="button">{{second}}秒后重新获取</span>
                    <span v-else class="get-captcha" slot="button" @click="getCaptcha()">获取验证码</span>
                </van-field>

                <van-field label="短信验证码" v-model="formInfo.captcha" required/>

                <van-field label="性别" required>
                    <van-radio-group v-model="formInfo.sex" slot="input">
                        <van-radio name="女">女</van-radio>
                        <van-radio name="男">男</van-radio>
                    </van-radio-group>
                </van-field>

                <van-field label="省/市/区" required>
                    <div slot="input" @click="clickArea()">
                        <span>上海市</span> -
                        <span>上海市</span> -
                        <span>{{countyInfo.name ? countyInfo.name : '请选择区'}}</span>
                    </div>
                </van-field>

                <van-field label="详细地址" required>
                    <input slot="input" class="van-field__control" v-model="formInfo.detailAddress" type="text"
                           placeholder="请输入**号**室" onfocus="this.placeholder=''"
                           onblur="this.placeholder='请输入**号**室'"/>
                </van-field>

                <van-field label="户口所在地(省/市)" required>
                    <div slot="input" @click="clickHukou()">
                        <span>{{hukouData[0].name ? hukouData[0].name : '请选择'}}</span> -
                        <span>{{hukouData[1].name ? hukouData[1].name : '请选择'}}</span>
                    </div>
                </van-field>

                <div v-if="showMoreInfo">
                    <van-field label-width="110px" label="最近回沪时间">
                        <div slot="input" @click="clickData()">
                            <span>{{$utils.date(backTime) ? $utils.date(backTime) : '请选择'}}</span>
                        </div>
                    </van-field>

                    <van-field label-width="110px" label="回沪交通方式">
                        <div slot="input" @click="clickTraffic()">
                            <span>{{trafficInfo ? trafficInfo : '请选择'}}</span>
                        </div>
                    </van-field>

                    <van-field label-width="110px" v-if="trafficInfo=='火车'" label="车次" v-model="formInfo.trainNumber"/>
                </div>

                <div class="more-info" @click="clickMoreInfo()">{{!showMoreInfo ? "更多信息" : "收起"}}</div>
            </van-cell-group>
        </div>


        <div class="btn-box">
            <van-button block @click="submit()">提交</van-button>
        </div>


        <!--省市区上拉弹框-->
        <van-action-sheet v-model="showAreaBox" title="选择省/市/区">
            <van-area :area-list="areaList" value="310000" @confirm="areaConfirm" @cancel="areaCancel"/>
        </van-action-sheet>

        <!--户口所在地上拉弹框-->
        <van-action-sheet v-model="showHukouBox" title="选择户口所在地">
            <van-area :columns-num="2" :area-list="hukouList" @confirm="hukouConfirm" @cancel="hukouCancel"/>
        </van-action-sheet>

        <!--最近回沪时间上拉弹框-->
        <van-action-sheet v-model="showDateBox" title="选择最近回沪时间">
            <van-datetime-picker type="date" :min-date="minDate" :max-date="maxDate"
                                 @confirm="dateConfirm" @cancel="dateCancel"/>
        </van-action-sheet>

        <!--回沪交通方式上拉弹框-->
        <van-action-sheet v-model="showTrafficBox" title="回沪交通方式">
            <van-picker show-toolbar :columns="trafficData" @cancel="trafficCancel" @confirm="trafficConfirm"/>
        </van-action-sheet>
    </div>
</template>

<script>
    import {NavBar, Field, CellGroup, Button, RadioGroup, Radio, Area, ActionSheet, DatetimePicker, Picker, Toast} from 'vant';
	import area from '../assets/js/area';

    export default {
        name: 'register',

        components: {
            [NavBar.name]: NavBar,
			[CellGroup.name]: CellGroup,
            [Field.name]: Field,
			[Button.name]: Button,
			[RadioGroup.name]: RadioGroup,
			[Radio.name]: Radio,
			[Area.name]: Area,
			[ActionSheet.name]: ActionSheet,
			[DatetimePicker.name]: DatetimePicker,
			[Picker.name]: Picker,
			[Toast.name]: Toast,
        },

        props: {

        },

        data() {
            return {
				timer: null,                //验证码计时器
				showCountdown: false,       //是否显示倒计时
				second: 60,               //重新获取剩余秒数

				showMoreInfo: false,      //是否显示更多

                //表单信息
            	formInfo: {
					personName: '',     //姓名
					personPhone: '',    //手机号
					captcha: '',       //短信验证码
					captchaType: '',      //验证码类型
                    sex: '男',            //性别
					detailAddress: '',     //详细地址
					trainNumber: '',     //车次
                },

				countyInfo: {
					code: '',
					name: '',
				},
				hukouData: [
					{code: '', name: ''},
					{code: '', name: ''},
				],
				backTime: '',            //最近回沪时间
				trafficInfo: '',   //回沪交通方式


                //上海区县列表
				areaList: {
					'province_list': {310000: '上海市'},
					'city_list': {310100: '上海市'},
					'county_list': {},
                },
				hukouList: area,
				showAreaBox: false,
				showHukouBox: false,


				showDateBox: false,
				minDate: new Date(2019, 0, 1),
				maxDate: new Date(2030, 11, 31),

				trafficData: ['火车','自驾','公共汽车','其他'],
				showTrafficBox: false,
            }
        },

        mounted() {
			//获取上海区县列表
			this.areaList['county_list'] = {...area['county_list']};

        },

        methods: {
			//尝试用openId登录
			tryLogin(){
				this.$axios.post(this.$api.loginById, {
					openId: this.$Cookies.get('openId'),

				}).then(success => {
					if(success.data.code == '200'){
						//把用户信息保存到cookie
						this.$Cookies.set('personName', success.data.data.personName);
						this.$Cookies.set('personId', success.data.data.personId);
						this.$Cookies.set('personPhone', success.data.data.personPhone);
						this.$Cookies.set('personRole', success.data.data.role);
						this.$Cookies.set('communityName', success.data.data.communityName);
						this.$Cookies.set('communityId', success.data.data.communityId);
                        this.goToURL();
					}
				}).catch(error => {

				})
			},

			//根据用户类型跳转到对应的主页
			goToURL(){
				let userType = this.$Cookies.get('userType');

				//userType: 1000 拜访者，2000 业主，3000物业管理
				switch(userType) {
					case '1000':
						this.$router.replace('/visit');
						break;

					case '2000':
						this.$router.replace('/owner');
						break;

					case '3000':
						//securityStaff保安; propertyManager经理;
						if(this.$Cookies.get('personRole') == 'securityStaff'){
							this.$router.replace('/securityManage');

						}else if(this.$Cookies.get('personRole') == 'propertyManager'){
							this.$router.replace('/propertyManage');

						}else{
							//点物业管理进来之后没有权限就跳到个人中心页
							this.$router.replace('/personalInfo');
						}
						break;

					default:
						Toast('无法识别用户类型');
						break;
				}
			},

			//点击提交
			submit(){
				//必填信息验证
				if(!this.formInfo.personName || !this.formInfo.personPhone || !this.formInfo.captcha
                   || !this.countyInfo.name || !this.formInfo.detailAddress || !this.hukouData[0].name){
					Toast('请录入必填信息');
					return;
                }

                //调用注册接口
				this.$axios.post(this.$api.registerInfo, {
					openId: this.$Cookies.get('openId'),         //微信openId
					personName: this.formInfo.personName,           //姓名
					personPhone: this.formInfo.personPhone,         //手机号
					captcha: this.formInfo.captcha,              //短信验证码
					captchaType: 'register',                     //验证码类型
					sex: this.formInfo.sex,                      //性别
					domicile: this.countyInfo.name,              //省/市/区
					detailAddress: this.formInfo.detailAddress,              //详细地址
					nativePlace: this.hukouData[0].name+this.hukouData[1].name,    //户口所在地(省/市)
					backTime: this.$utils.date(this.backTime),       //最近回沪时间
					traffic: this.trafficInfo,                         //回沪交通方式
					trainNumber: this.formInfo.trainNumber,            //车次

				}).then(success => {
					if(success.data.code == '200'){
						Toast('注册成功');
						this.tryLogin();
                    }
				}).catch(error => {

				})
			},

            //点击获取验证码
			getCaptcha(){
				if(!this.formInfo.personPhone){
					Toast('请输入手机号');
					return;
                }

				this.$axios.post(this.$api.sendSmsCaptcha, {
					telNo: this.formInfo.personPhone,
					captchaType: 'register',

				}).then(success => {
					if(success.data.code == '200'){
						Toast('发送成功');
						this.startCountdown();
					}
				}).catch(error => {

				})
            },
			//开始倒计时
			startCountdown(){
				this.showCountdown = true;
				this.second = 60;
				clearInterval(this.timer);

				this.timer = setInterval(() => {
					if(this.second == 1){
						clearInterval(this.timer);
						this.showCountdown = false;
                    }else{
						this.second -= 1;
                    }
                },1000)
            },

            //点击返回
			onClickLeft(){
				this.$router.go(-1);
			},

			//点击更多信息
			clickMoreInfo(){
				this.showMoreInfo = !this.showMoreInfo;
			},

			//点击选择省/市/区
			clickArea(){
				this.showAreaBox = true;
			},
			areaConfirm(data){
				this.countyInfo = data[2];
				this.showAreaBox = false;
			},
			areaCancel(){
				this.showAreaBox = false;
			},

            //点击选择户口所在地
			clickHukou(){
				this.showHukouBox = true;
            },
			hukouConfirm(data){
				this.hukouData = data;
				this.showHukouBox = false;
            },
			hukouCancel(){
				this.showHukouBox = false;
			},

            //点击选择返沪时间
            clickData(){
				this.showDateBox = true;
            },
			dateConfirm(date){
				this.showDateBox = false;
				this.backTime = date;
            },
			dateCancel(){
				this.showDateBox = false;
			},

            //点击回沪交通方式
			clickTraffic(){
				this.showTrafficBox = true;
            },
			trafficConfirm(data){
				this.showTrafficBox = false;
				this.trafficInfo = data;

				//选择非火车清空车次
				if(data !== '火车'){
					this.formInfo.trainNumber = '';
				}
			},
			trafficCancel(){
				this.showTrafficBox = false;
			},
        },
    }
</script>

<style lang="scss" scoped>
    /*表单样式覆盖*/
    .van-cell-group{
        background-color: transparent;

        &::after {
            border: none;
        }

        .van-cell{
            background-color: transparent;
            border-bottom: 1px solid #ebedf0;
            padding-top: 16px;
            padding-bottom: 16px;
            font-size: 15px;
            color: #222222;

            &::after {
                border: none;
            }
        }
        .van-cell--required::before{
            color: #222222;
        }
    }

    /*获取验证码样式*/
    .get-captcha{
        font-size: 15px;
        color: #61dda3;
    }
    /*选择性别*/
    .van-radio{
        float: right;
        width: 70px;
    }

    /*更多信息*/
    .more-info{
        font-size: 15px;
        text-align: center;
        color: #999999;
        padding: 16px 10px;
    }

    /*提交按钮*/
    .btn-box{
        width: 94%;
        margin: 0 auto;
        margin-top: 40px;

        .van-button--default {
            background: linear-gradient(to bottom right, #61dda3, #07b6d5);
            border-radius: 8px;
        }
        .van-button__text{
            font-size: 18px;
            font-weight: bold;
            color: white;
        }
    }
</style>

